"""
模拟Java中的g.b()函数，实现RC4加密算法
"""

class RC4State:
    """模拟Java中的a类"""
    def __init__(self):
        self.a = [0] * 256  # 对应Java中的int[] a
        self.x = 0          # 对应Java中的int x
        self.y = 0          # 对应Java中的int y

def init_rc4_state(key_str):
    """
    模拟Java中的a(String str)方法
    初始化RC4状态
    
    Args:
        key_str: 密钥字符串
        
    Returns:
        RC4State: 初始化的RC4状态
    """
    if key_str is None:
        return None
    
    state = RC4State()
    
    # 初始化状态数组
    for i in range(256):
        state.a[i] = i
    
    state.x = 0
    state.y = 0
    
    j = 0
    k = 0
    
    # 使用密钥打乱状态数组
    for i in range(256):
        try:
            char_code = ord(key_str[j])
            k = (char_code + state.a[i] + k) % 256
            
            # 交换state.a[i]和state.a[k]
            temp = state.a[i]
            state.a[i] = state.a[k]
            state.a[k] = temp
            
            j = (j + 1) % len(key_str)
        except Exception:
            return None
    
    return state

def process_data(data, state):
    """
    模拟Java中的a(byte[] bArr, a aVar)方法
    使用RC4算法处理数据
    
    Args:
        data: 要处理的字节数据
        state: RC4状态
        
    Returns:
        bytes: 处理后的字节数据
    """
    if data is None or state is None:
        return None
    
    i = state.x
    j = state.y
    
    # 创建可修改的字节数组
    result = bytearray(data)
    
    # 使用RC4算法处理每个字节
    for k in range(len(result)):
        i = (i + 1) % 256
        j = (state.a[i] + j) % 256
        
        # 交换state.a[i]和state.a[j]
        temp = state.a[i]
        state.a[i] = state.a[j]
        state.a[j] = temp
        
        # 计算异或索引
        t = (state.a[i] + state.a[j]) % 256
        
        # 异或操作
        result[k] = result[k] ^ state.a[t]
    
    state.x = i
    state.y = j
    
    return bytes(result)

def process_with_key(data):
    """
    模拟Java中的b(byte[] bArr)方法
    使用固定密钥处理数据
    
    Args:
        data: 要处理的字节数据
        
    Returns:
        bytes: 处理后的字节数据
    """
    # 使用与Java代码相同的密钥字符串
    key_str = "QrMgt8GGYI6T52ZY5AnhtxkLzb8egpFn3j5JELI8H6wtACbUnZ5cc3aYTsTRbmkAkRJeYbtx92LPBWm7nBO9UIl7y5i5MQNmUZNf5QENurR5tGyo7yJ2G0MBjWvy6iAtlAbacKP0SwOUeUWx5dsBdyhxa7Id1APtybSdDgicBDuNjI0mlZFUzZSS9dmN8lBD0WTVOMz0pRZbR3cysomRXOO1ghqjJdTcyDIxzpNAEszN8RMGjrzyU7Hjbmwi6YNK"
    
    state = init_rc4_state(key_str)
    if data is None or state is None:
        return None
    
    return process_data(data, state)

if __name__ == "__main__":
    # 测试代码
    test_data = b"Hello, World!"
    processed = process_with_key(test_data)
    print(f"原始数据: {test_data}")
    print(f"处理后: {processed}")
    
    # 验证处理两次会恢复原始数据（RC4的特性）
    restored = process_with_key(processed)
    print(f"再次处理: {restored}")
    print(f"是否恢复原始数据: {restored == test_data}")
